package com.lzf.filter;

import com.lzf.exception.KaptchaCodeException;
import com.lzf.handler.MyAuthenticationEntryPoint;
import com.lzf.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class KaptchaCodeFilter extends OncePerRequestFilter {
    @Autowired
    private MyAuthenticationEntryPoint myAuthenticationEntryPoint;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String ip = request.getHeader("X-Real-IP");
        String code = request.getParameter("code"); //验证码
        if (StringUtils.pathEquals("/oauth/token", request.getRequestURI())) {
            //放行  刷新token模式也是调用登录接口，
            if(StringUtils.pathEquals("refresh_token", request.getParameter("grant_type"))) {
                filterChain.doFilter(request,response);
                return;
            }
            if(StringUtils.isEmpty(code) || !RedisUtils.hasKey(ip)) {
                myAuthenticationEntryPoint.commence(request,response,new KaptchaCodeException("验证码错误或已失效"));
                return;
            }
            if(!code.equals(RedisUtils.get(ip))) {
                myAuthenticationEntryPoint.commence(request,response,new KaptchaCodeException("验证码错误或已失效"));
                RedisUtils.del(ip);
                return;
            }else {
                RedisUtils.del(ip);
            }


        }
        filterChain.doFilter(request,response);
    }
}
